package com.chen.palmar.project.init;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.Toast;

import com.alipay.sdk.app.AuthTask;
import com.chen.palmar.R;
import com.chen.palmar.base.BaseActivity;
import com.chen.palmar.common.datasource.DataCenter;
import com.chen.palmar.common.override.HttpSubscriber;
import com.chen.palmar.common.utils.OrderInfoUtil;
import com.chen.palmar.entity.AuthResult;
import com.chen.palmar.entity.LoginEntity;
import com.flyco.dialog.widget.NormalDialog;
import com.primb.androidlibs.ui.PasswordEditText;
import com.primb.androidlibs.utils.NetWorkUtils;
import com.primb.androidlibs.utils.PreferencesUtils;
import com.primb.androidlibs.utils.ToastUtils;
import com.tbruyelle.rxpermissions.RxPermissions;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.SendAuth;
import com.tencent.mm.sdk.openapi.WXAPIFactory;

import java.util.HashMap;
import java.util.Map;

import butterknife.Bind;
import butterknife.OnClick;
import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.tencent.qq.QQ;
import rx.Subscription;

import static com.chen.palmar.common.constant.AppConstant.APP_WX_ID;

public class LoginActivity extends BaseActivity {

    @Bind(R.id.et_user)
    EditText etUser;
    @Bind(R.id.et_pwd)
    PasswordEditText etPwd;
    private boolean isPermission = false;
    /**
     * 支付宝支付业务：入参app_id
     */
    public static final String APPID = "2018011801946697";

    /**
     * 支付宝账户登录授权业务：入参pid值
     */
    public static final String PID = "2088421561515699";
    /**
     * 支付宝账户登录授权业务：入参target_id值
     */
    public static String TARGET_ID = "";

    /** 商户私钥，pkcs8格式 */
    /** 如下私钥，RSA2_PRIVATE 或者 RSA_PRIVATE 只需要填入一个 */
    /** 如果商户两个都设置了，优先使用 RSA2_PRIVATE */
    /** RSA2_PRIVATE 可以保证商户交易在更加安全的环境下进行，建议使用 RSA2_PRIVATE */
    /** 获取 RSA2_PRIVATE，建议使用支付宝提供的公私钥生成工具生成， */
    /**
     * 工具地址：https://doc.open.alipay.com/docs/doc.htm?treeId=291&articleId=106097&docType=1
     */
    public static final String RSA2_PRIVATE = "MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQCbydz8VKgcZSRniNFJzb2eqCgIjoqRgiQgJ49uOButCTGGYjAV3Jyy6YeFNTRvst70VBRiJbvmpg8YPe+ALC5BwGLdyw4a2zVodD62W0n0mgdJUPlwl9F2dJ4omRwFYQvws7XXKaVvFUdcIwL6Xx8XNYRwVApw5yxWc/K7Lc9peC4pmk1a12PxlG+6kDAVR/3OrZTE7E2dVPQUvbu9jP8TNbq03UBDchDAE3knT0HFR8eI0FvlnLc9WWWCJdxIdcwyq3/Roi8uLmjI4FURRqofAWIhX5nC5dxvwlcxJe1Q1EFnp1lB4sLKYsiDb0nfptVH0ax3n9AdaAwp8sTbYhYVAgMBAAECggEACrCaUlI4yuIB0nzn54mPlmBxhszJI1zrv60XQXfmJkR4OoFoTUe7FOfDXdedxoBeniNa1rVCJHyGkqJFWeUuM2LRJej2Cc+65XT8jKTM+VTMZTKCO0CfpeIwrBZ9frz/BcA/HQmFiY7LO75HSQjX6E7KzK5nnQGv4CrKoB9vmQwDibTtKAuJZ3OQoovG7MbIK51CgYSzdIS51GrKUV0FbtpeJDMrqR4/gUSyi42oJWcO1WnHvL527coSE2h8Xa1eV6DEtWJcoLKVTbG/1nfGv2856L6EcH2nFbW7iMnBfD91AFMhLdgwve6nsncCUNXg7pPt5p9+OcgsgwXON5OtrQKBgQDdTBJrFP9FPFU0V98zFTq2UY4k5LckAffI2+HwNlxugQXX71quOynre/wettfr/7RR3ZF3WNF69sneutSEZjTJC4VXR75qA3O/mCg5B0u8a8Go4W79gKIx9DN3fmEqCUu/ZJ/vVHhFQpn2oz9sqJz99/cfjKJ93akI0+yJCYkQLwKBgQC0N/YLi+G3C34wKiO52hkuE6t4Xtusz444TqBSUnTGUTAdJWn8aYSfkoZfCT8NL8o1tpiZ1QXGXZ21fP8KOe+4PMZjZG2ITwlVb2SCuP7JiiYzapxZJEI1wxGQXp09cbgkNXVst+I7JZAkTIkUuj5l1KwDlDXqSPIPR4v/gy5I+wKBgD9FqtZ3EG2JTItEvIpsfXb3Zn7h7gMblO8W/0ihIlhuB2+v/etm+xtbPcDCYoYVfEcT5K2M9YgE278VCAI6/sikxKEp4CWLiyKyrH1xupPK83oHyqYsizNhMP3vYnSUZ9X3PUs+iYyz+DVug4nbw9dReJTKrwLxx4zAmxarZUb9AoGAcqJSEKAmsD9QQiTb2sE/WQ7L+GImS7MunORumE641tkXyMJeu18HLFWQwWzpPWMTtbzzLo7RAI/V3Hao6AFYWZHXA6wC/DyCDGUxwvEXqG0GxZff4dftgbMWPgXg8Q+f+PBERCZncgX/vQct/xBE1pND43boIKHLzypMg/gWffcCgYAo+BNpqjDgR0GLDf+ZaX/UcA/eWP6RJkBV33083Opywjdue/X1lE2wBjZXKveClDljcSd8R9D2NsHTENzn88x66fxtjWOuEr9GmjObXWqVG56utSc9+oDEu12cF71499O8KbEjaVGidkRlQXH3hJeUJl++IBDTN/7uWQzdWG2CZA==";
    private static final int SDK_PAY_FLAG = 1;
    private static final int SDK_AUTH_FLAG = 2;
    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @Override
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_AUTH_FLAG: {
                    @SuppressWarnings("unchecked") AuthResult authResult = new AuthResult((Map<String, String>) msg.obj, true);
                    String resultStatus = authResult.getResultStatus();

                    // 判断resultStatus 为“9000”且result_code
                    // 为“200”则代表授权成功，具体状态码代表含义可参考授权接口文档
                    if (TextUtils.equals(resultStatus, "9000") && TextUtils.equals(authResult.getResultCode(), "200")) {
                        // 获取alipay_open_id，调支付时作为参数extern_token 的value
                        // 传入，则支付账户为该授权账户
                        otherLogin(authResult.getAlipayOpenId(), "3");

                        Toast.makeText(LoginActivity.this, "授权成功", Toast.LENGTH_SHORT).show();
                    } else {
                        // 其他状态值则为授权失败
                        Toast.makeText(LoginActivity.this, "授权失败", Toast.LENGTH_SHORT).show();
                    }
                    break;
                }
                default:
                    hideLoading();
                    break;
            }
        }

        ;
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        super.onCreate(savedInstanceState);
        init();
    }

    @Override
    public void init() {
        getPermissions(true);

        etUser.setText(PreferencesUtils.getString(this, "user"));
        etUser.setSelection(etUser.getText().length());
        etPwd.setText("");

        TARGET_ID = OrderInfoUtil.getOutTradeNo();
    }

    /**
     * 获取权限
     *
     * @param isShowDialog 是否显示对话框
     */
    private void getPermissions(boolean isShowDialog) {
        RxPermissions rxPermissions = new RxPermissions(this);
        if (!rxPermissions.isGranted(Manifest.permission.ACCESS_NETWORK_STATE)
                || !rxPermissions.isGranted(Manifest.permission.READ_EXTERNAL_STORAGE)
                || !rxPermissions.isGranted(Manifest.permission.READ_PHONE_STATE)
                || !rxPermissions.isGranted(Manifest.permission.CALL_PHONE)
                || !rxPermissions.isGranted(Manifest.permission.ACCESS_COARSE_LOCATION)
                || !rxPermissions.isGranted(Manifest.permission.ACCESS_FINE_LOCATION)
                || !rxPermissions.isGranted(Manifest.permission.CAMERA)) {
            if (isShowDialog) {
                NormalDialog dialog = showAlterDialog("请求权限", "请确认使用APP的必要权限");
                dialog.setOnBtnClickL(() -> {
                    dialog.dismiss();
                }, () -> {
                    rxPermissions.request(Manifest.permission.ACCESS_NETWORK_STATE,
                            Manifest.permission.READ_EXTERNAL_STORAGE,
                            Manifest.permission.READ_PHONE_STATE,
                            Manifest.permission.ACCESS_COARSE_LOCATION,
                            Manifest.permission.ACCESS_FINE_LOCATION,
                            Manifest.permission.CALL_PHONE,
                            Manifest.permission.CAMERA).subscribe(aBoolean -> {
                        if (aBoolean) {
                            DataCenter.configDeviceInfo();
                            showToast("请求成功");
                            isPermission = true;
                        } else {
                            showToast("请求权限失败");
                        }
                    });
                    dialog.dismiss();
                });
            } else {
                rxPermissions.request(Manifest.permission.ACCESS_NETWORK_STATE,
                        Manifest.permission.READ_EXTERNAL_STORAGE,
                        Manifest.permission.READ_PHONE_STATE,
                        Manifest.permission.ACCESS_COARSE_LOCATION,
                        Manifest.permission.ACCESS_FINE_LOCATION,
                        Manifest.permission.CALL_PHONE,
                        Manifest.permission.CAMERA).subscribe(aBoolean -> {
                    if (aBoolean) {
                        showToast("请求成功");
                        isPermission = true;
                    } else {
                        showToast("请求权限失败");
                    }
                });
            }
        } else {
            isPermission = true;
            DataCenter.configDeviceInfo();
        }
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_login;
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            NormalDialog dialogExit = showAlterDialog("退出提示", "是否退出登录？");
            dialogExit.setOnBtnClickL(null, () -> exit());
        }
        return false;
    }

    private void loginToSelf() {
        String pwd = etPwd.getText().toString();
        String user = etUser.getText().toString();
        if (user.equals("") || pwd.equals("")) {
            showToast("账号或密码为空，请完善后登陆");
        } else {
            if (!isPermission) {
                NormalDialog dialog = showAlterDialogOne("权限提示", "未获得应用所需权限，请点击确认获取权限");
                dialog.setCancelable(false);
                dialog.setOnBtnClickL(() -> {
                    dialog.dismiss();
                    getPermissions(false);
                });
                return;
            }
            PreferencesUtils.putString(this, "user", user);
            HashMap<String, String> map = new HashMap<>();
            map.put("mobile", user);
            map.put("password", pwd);
            Subscription subscribe = DataCenter.login(map).subscribe(new HttpSubscriber<LoginEntity>(this, showLoading("登录中")) {
                @Override
                public void onNext(LoginEntity loginEntity) {
                    DataCenter.httpConfig.setUserId(loginEntity.getData().getUserId());
                    DataCenter.httpConfig.setLoginToken(loginEntity.getData().getAnycode());
                    Intent intent = new Intent();
                    if (TextUtils.isEmpty(loginEntity.getData().getSex()) || TextUtils.isEmpty(loginEntity.getData().getType())) {
                        intent.setClass(LoginActivity.this, IdentityActivity.class);
                    } else {
                        intent.setClass(LoginActivity.this, MainActivity.class);
                        intent.putExtra("info", loginEntity.getData());
                    }
                    startActivity(intent);
                }
            });
            subscription.add(subscribe);
        }
    }

    @OnClick({R.id.btn_login, R.id.tv_wx, R.id.tv_qq, R.id.tv_zfb, R.id.tv_register, R.id.tv_forget})
    public void onViewClicked(View view) {
        if (!isPermission) {
            NormalDialog dialog = showAlterDialogOne("权限提示", "未获得应用所需权限，请点击确认获取权限");
            dialog.setCancelable(false);
            dialog.setOnBtnClickL(() -> {
                dialog.dismiss();
                getPermissions(false);
            });
            return;
        }
        switch (view.getId()) {
            case R.id.btn_login:
                if (NetWorkUtils.isNetworkConnected()) {
                    loginToSelf();
                } else {
                    showToast("请连接网络后登陆");
                }
                break;
            case R.id.tv_wx:
                showLoading("登录中");
                loginToWechat();
                break;
            case R.id.tv_qq:
                Platform qq = ShareSDK.getPlatform("QQ");
                if ("QQ".equals(qq.getName()) && !qq.isClientValid()) {
                    ToastUtils.showShort("当前手机未安装QQ");
                    return;
                }
                showLoading("登录中");
                loginToQQ("QQ");
                break;
            case R.id.tv_zfb:
                showLoading("登录中");
                loginToZfb();
                break;
            case R.id.tv_register:
                Intent intent = new Intent(this, RegisterActivity.class);
                intent.putExtra("isRegister", true);
                startActivity(intent);
                break;
            case R.id.tv_forget:
                Intent intentF = new Intent(this, RegisterActivity.class);
                intentF.putExtra("isRegister", false);
                startActivity(intentF);
                break;
        }
    }

    //微信授权登录
    private void loginToWechat() {
        //微信接入
        IWXAPI wxapi = WXAPIFactory.createWXAPI(this, APP_WX_ID, true);
        wxapi.registerApp(APP_WX_ID);

        if (wxapi != null && wxapi.isWXAppInstalled()) {
            SendAuth.Req req = new SendAuth.Req();
            req.scope = "snsapi_userinfo";//获取个人用户信息的权限
            req.state = "wechat_sdk_demo_test";//防止攻击
            boolean isSend = wxapi.sendReq(req);//向微信发送请求
            System.out.println(isSend);
        } else {
            showToast("当前手机未安装微信");
        }
    }

    private void loginToQQ(String platform) {
        Platform platformObj = ShareSDK.getPlatform(platform);
        //回调信息，可以在这里获取基本的授权返回的信息，但是注意如果做提示和UI操作要传到主线程handler里去执行
        platformObj.setPlatformActionListener(new PlatformActionListener() {

            @Override
            public void onError(Platform arg0, int arg1, Throwable arg2) {
                // TODO Auto-generated method stub
                arg2.printStackTrace();
            }

            @Override
            public void onComplete(Platform arg0, int arg1, HashMap<String, Object> arg2) {
                if ("QQ".equals(platform)) {
                    otherLogin(arg0.getDb().getUserId(), "1");
                }
            }

            @Override
            public void onCancel(Platform arg0, int arg1) {

            }
        });
//authorize与showUser单独调用一个即可
//        platformObj.authorize();//单独授权,OnComplete返回的hashmap是空的
        platformObj.showUser(null);//授权并获取用户信息
    }

    private void loginToZfb() {
        /**
         * 这里只是为了方便直接向商户展示支付宝的整个支付流程；所以Demo中加签过程直接放在客户端完成；
         * 真实App里，privateKey等数据严禁放在客户端，加签过程务必要放在服务端完成；
         * 防止商户私密数据泄露，造成不必要的资金损失，及面临各种安全风险；
         *
         * authInfo的获取必须来自服务端；
         */
        boolean rsa2 = (RSA2_PRIVATE.length() > 0);
        Map<String, String> authInfoMap = OrderInfoUtil.buildAuthInfoMap(PID, APPID, TARGET_ID, rsa2);
        String info = OrderInfoUtil.buildOrderParam(authInfoMap);

        String privateKey = RSA2_PRIVATE;
        String sign = OrderInfoUtil.getSign(authInfoMap, privateKey, rsa2);
        final String authInfo = info + "&" + sign;
        Runnable authRunnable = new Runnable() {

            @Override
            public void run() {
                // 构造AuthTask 对象
                AuthTask authTask = new AuthTask(LoginActivity.this);
                // 调用授权接口，获取授权结果
                Map<String, String> result = authTask.authV2(authInfo, true);

                Message msg = new Message();
                msg.what = SDK_AUTH_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };

        // 必须异步调用
        Thread authThread = new Thread(authRunnable);
        authThread.start();
    }

    private void otherLogin(String userId, String type) {
        HashMap<String, String> map = new HashMap<>();
        map.put("open_id", userId);
        map.put("type", type);
        Subscription subscribe = DataCenter.otherLoginInfo(map).subscribe(new HttpSubscriber<LoginEntity>(this, showLoading("登录中")) {
            @Override
            public void onNext(LoginEntity loginEntity) {
                DataCenter.httpConfig.setUserId(loginEntity.getData().getUserId());
                DataCenter.httpConfig.setLoginToken(loginEntity.getData().getAnycode());
                Intent intent = new Intent();
                if (TextUtils.isEmpty(loginEntity.getData().getType())) {
                    intent.setClass(LoginActivity.this, IdentityActivity.class);
                } else {
                    intent.setClass(LoginActivity.this, MainActivity.class);
                    intent.putExtra("info", loginEntity.getData());
                }
                startActivity(intent);
            }
        });
        subscription.add(subscribe);
    }

    @Override
    public void onPause() {
        super.onPause();
        if (spotsDialog != null && spotsDialog.isShowing()) {
            hideLoading();
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
        if (etPwd != null) {
            etPwd.setText("");
        }
    }
}
